<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import * as echarts from 'echarts'
import axios from 'axios'
// 引入百度地图扩展
import 'echarts/extension/bmap/bmap'


// 查询参数
const timeType = ref('小时')
const trafficType = ref('总流量')
const operator = ref('ALL')
const networkType = ref('ALL')

const dateMinusDay = (date, days) => {
  const d = new Date(date)
  d.setDate(d.getDate() - days)
  return d
}
const lastWeek = dateMinusDay(new Date(), 7)
// 添加日期范围ref
const dateRange = ref({ start: lastWeek, end: new Date() })

// 下拉选项
const timeTypeOptions = ['小时', '天', '月']

const trafficTypeOptions = ['总流量', '上行流量', '下行流量']

const operatorOptions = ['ALL', 'CMCC', 'CTCC', 'CUCC']

const networkTypeOptions = ['ALL', '4G', '3G', '2G']

// 提交查询
const submitQuery = () => {
  fetchChartData()
}

const chartRef = ref<HTMLElement | null>(null)
let chart: echarts.ECharts | null = null

// 添加 APP 图标映射
const appIcons = {
  '抖音': 'image:///icon/抖音.svg',
  '淘宝': 'image:///icon/淘宝.svg',
  '微信': 'image:///icon/微信.svg',
  // 可以添加更多 APP 的图标
}

const convertData = function (data) {
  const res = []
  for (const item of data) {
    res.push({
      name: item.name,
      value: [item.longitude, item.latitude, item.value],
      symbol: appIcons[item.name] || 'circle', // 使用对应的图标或默认圆形
      symbolSize: [24, 24], // 调整图标大小
      symbolOffset: [0, -12], // 可选：调整图标位置偏移
    })
  }
  return res
}

const fetchChartData = async () => {
  try {
    const params = {
      dateRange: dateRange.value,
      timeType: timeType.value,
      trafficType: trafficType.value,
      operator: operator.value,
      networkType: networkType.value,
    }

    const response = await axios.get('/api/data/rate/distribution', { })
    console.log(response)
    const mockData = response.data.data
    console.log(mockData)

    if (!chart || !chartRef.value) return

    const option = {
      backgroundColor: 'transparent',
      bmap: {
        center: [104.114129, 37.550339],
        zoom: 5,
        roam: true,
        mapStyle: {
          styleJson: []
        }
      },
      series: [
        {
          name: '连接成功',
          type: 'scatter',
          coordinateSystem: 'bmap',
          data: mockData.success.map(item => ({
            value: [item.longitude, item.latitude],
            itemStyle: { color: '#5DE15E' },
            symbol: 'circle',
            symbolSize: 8
          }))
        },
        {
          name: '连接失败',
          type: 'scatter',
          coordinateSystem: 'bmap',
          data: mockData.failure.map(item => ({
            value: [item.longitude, item.latitude],
            itemStyle: { color: '#F50001' },
            symbol: 'circle',
            symbolSize: 8
          }))
        }
      ]
    }
    console.log(option.series)

    chart.setOption(option)
  } catch (error) {
    console.error('获取图表数据失败:', error)
  }
}

const initChart = () => {
  if (!chartRef.value) return
  chart = echarts.init(chartRef.value)
  fetchChartData()
}

onMounted(() => {
  initChart()
  window.addEventListener('resize', () => {
    chart?.resize()
  })
})

// 当任何查询参数变化时重新获取数据
watch([dateRange, timeType, trafficType, operator, networkType], () => {
  fetchChartData()
})
</script>

<template>
  <!-- <h1 class="page-title">热门APP地图</h1> -->

  <VaCard>
    <VaCardContent>
      <div class="flex flex-col justify-between gap-2 mb-4 md:flex-row">
        <div class="flex flex-col justify-start gap-2 md:flex-row">
          <VaDateInput v-model="dateRange" mode="range" label="日期范围" placeholder="日期范围" />
          <VaSelect v-model="timeType" :options="timeTypeOptions" label="时间粒度" placeholder="时间粒度" />
          <VaSelect v-model="trafficType" :options="trafficTypeOptions" label="流量类型" placeholder="流量类型" />
          <VaSelect v-model="operator" :options="operatorOptions" label="运营商" placeholder="运营商" />
          <VaSelect v-model="networkType" :options="networkTypeOptions" label="网络类型" placeholder="网络类型" />
        </div>
        <div class="flex gap-2">
          <VaButton @click="submitQuery">查询</VaButton>
        </div>
      </div>
      <!-- ECharts 容器 -->
      <div ref="chartRef" style="width: 100%; height: calc(100vh - 245px)"></div>
    </VaCardContent>
  </VaCard>
</template>

<style>
.va-date-input {
  width: 200px;
}
.va-select {
  width: 180px;
}
.va-button {
  margin-top: 16px;
  height: 35px;
  width: 80px;
}
</style>
